package com.util.excel;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import org.apache.poi.ss.usermodel.*;

import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

/**
 * @Description: 根据条件高亮
 * @Author: hechaobo
 * @Date: 2024/3/12
 **/
public class HighLightHandler implements CellWriteHandler {

    /**
     * 高亮的列，高亮条件
     */
    Map<Integer, Predicate<Cell>> map;
    public HighLightHandler(Map<Integer, Predicate<Cell>> map){
        this.map = map;
    }
    CellStyle cellStyle;
    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        if(!isHead){
            int columnIndex = cell.getColumnIndex();
            if (map.containsKey(columnIndex)) {
                try {
                    if (map.get(columnIndex).test(cell)) {
                        WriteCellStyle orCreateStyle = cellDataList.get(0).getOrCreateStyle();

                        orCreateStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
                        orCreateStyle.setFillForegroundColor(IndexedColors.RED.index);
                        orCreateStyle.setBorderBottom(BorderStyle.THIN);
                        orCreateStyle.setBorderLeft(BorderStyle.THIN);
                        orCreateStyle.setBorderRight(BorderStyle.THIN);
                        orCreateStyle.setBorderTop(BorderStyle.THIN);

                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
